<?
if (!defined('IN_DISCUZ')){
	exit('Access Denied');
}
define('NOROBOT', TRUE);

if (!$_G['setting']['search']['shop']['status']){
	showmessage('search_shop_closed');
}

$_G['setting']['search']['shop']['searchctrl'] = intval($_G['setting']['search']['shop']['searchctrl']);

$srchmod = 7;
$cachelife_time = 300;
$cachelife_text = 3600;

$searchid = isset($_G['gp_searchid']) ? intval($_G['gp_searchid']) : 0;
$srchfrom = intval($_G['gp_srchfrom']);
$srchtxt  = $_G['gp_srchtxt']; //echo $srchtxt;
$keyword  = isset($srchtxt) ? htmlspecialchars(trim($srchtxt)) : ''; //echo $keyword ;

//$srchkw = $_G['gp_kw'];
//$kw		= isset($srchkw) ? htmlspecialchars(trim($srchkw)) : '';
//$extKw	= $kw ? $kw : $srchtxt;
//$kwhtm	= str_replace(' ', '+', $extKw);

//$before = intval($_G['gp_before']);
//$srchsid = $_G['gp_srchsid'];
//$srhsid = intval($_G['gp_srhsid']);

if (!submitcheck('searchsubmit', 1)){
	if ($_G['gp_adv']){
		require libfile('function/shoplist');
		$catSelect = shopselect();
		
		if (!empty($srchsid) && !is_numeric($srchsid)){
			$catSelect = str_replace('<option value="' . $srchsid . '">', '<option value="' . $srchsid . '" selected="selected">', $catSelect);
		}
		// Form tim kiem nang cao
		include template('search/shop_adv');
	}else{
		// Form tim kiem thuong
		include template('search/shop');
	}
}else{

	$orderby = in_array($_G['gp_orderby'], array(
			'dateline'
	)) ? $_G['gp_orderby'] : 'lastpost';

	$ascdesc = isset($_G['gp_ascdesc']) && $_G['gp_ascdesc'] == 'asc' ? 'asc' : 'desc';

	if (!empty($searchid)){

		$page = max(1, intval($_G['gp_page']));
		$start_limit = ($page - 1) * $_G['tpp'];

		$index = DB::fetch_first("SELECT searchstring, keywords, num, ids
								  FROM " . DB::table('common_searchindex') . "
								  WHERE searchid='$searchid' AND srchmod='$srchmod'");

		if (!$index){
			showmessage('search_id_invalid');
		}

		$keyword = htmlspecialchars($index['keywords']);
		$keyword = $keyword != '' ? str_replace('+', ' ', $keyword) : '';
		$index['keywords'] = rawurlencode($index['keywords']);

		$prolist = array();
		$pricount = 0;

		$Qry = "SELECT p.pid, p.cid, p.uid, p.view, p.username, p.pname, p.punit,p.location_province, p.pcode, p.sales, p.state, p.b_sales, p.e_sales, p.total_vote, p.vote,
				p.img_cover, p.lastupdate,p.pprice,p.summary, d.name as province, a.attachment, a.remote
				FROM " . DB::table("shop_products") . " p
				LEFT JOIN " . DB::table("common_district") . " d ON p.location_province = d.id
				LEFT JOIN " . DB::table("shop_products_attachment") . " a ON p.img_cover = a.aid
				WHERE p.pid IN($index[ids])
				LIMIT $start_limit, $_G[tpp]";

		$query = DB::query($Qry);
		while ($row = DB::fetch($query)){
			$row['prname'] = bat_highlight($row['pname'], $keyword);
			$row['imgcoverthumb'] = ($row['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'shop/' . substr($row['attachment'], 0, 10) . $row['img_cover'] . '.thumb.jpg';

			if ($row['sales']){
				$row['end_price'] = ($row['pprice'] - (doubleval($row['pprice']) * doubleval($row['sales'])) / 100);
				$row['end_price'] = FormatNumber($row['end_price']);
				$row['sales'] = FormatNumber($row['sales'], 2, '.', ',', FALSE);
			}else
				$row['end_price'] = FormatNumber($row['pprice']);

			$prolist[] = $row;
		}

		$multipage = multi($index['num'], $_G['tpp'], $page, "search.php?mod=shop&searchid=$searchid&orderby=$orderby&ascdesc=$ascdesc&searchsubmit=yes");

		$url_forward = 'search.php?mod=shop&'.$_SERVER['QUERY_STRING']; //echo $url_forward;

		include template('search/shop');
	}else{

		$searchstring = 'shop|title|' . base64_encode($extKw) . '|' . intval($srchfrom);
		$searchindex = array(
				'id'=>0,
				'dateline'=>'0'
		);

		$Qry = "SELECT searchid, dateline,
				('" . $_G['setting']['search']['shop']['searchctrl'] . "'<>'0' AND " . (empty($_G['uid']) ? "useip='$_G[clientip]'" : "uid='$_G[uid]'") . " AND $_G[timestamp]-dateline<'" . $_G['setting']['search']['shop']['searchctrl'] . "') AS flood,
				(searchstring='$searchstring' AND expiration>'$_G[timestamp]') AS indexvalid
				FROM " . DB::table('common_searchindex') . "
				WHERE srchmod='$srchmod' AND ('" . $_G['setting']['search']['shop']['searchctrl'] . "'<>'0' AND " . (empty($_G['uid']) ? "useip='$_G[clientip]'" : "uid='$_G[uid]'") . " AND $_G[timestamp]-dateline<" . $_G['setting']['search']['shop']['searchctrl'] . ") OR (searchstring='$searchstring' AND expiration>'$_G[timestamp]')
				ORDER BY flood";
//echo $Qry;
//exit();

		$query = DB::query($Qry);

		while ($index = DB::fetch($query)){
			if ($index['indexvalid'] && $index['dateline'] > $searchindex['dateline']){
				$searchindex = array(
						'id'=>$index['searchid'],
						'dateline'=>$index['dateline']
				);
				break;
			}elseif ($_G['adminid'] != '1' && $index['flood']){
				showmessage('search_ctrl', 'search.php?mod=shop', array(
						'searchctrl'=>$_G['setting']['search']['shop']['searchctrl']
				));
			}
		}

		if ($searchindex['id']){
			$searchid = $searchindex['id'];
		}else{

			$mySelect = '';
			$mySqli = '';
			$myOrder = 'lastupdate DESC';
			$condition = '(pprice > 2000 OR uid = ' . $_G[uid] . ')';

			if ($_G['adminid'] != 1)
				$condition .= ' AND available = 1';

			if ($_G['adminid'] != '1' && $_G['setting']['search']['shop']['maxspm']){
				if ((DB::result_first("SELECT COUNT(*)
										FROM " . DB::table('common_searchindex') . "
										WHERE srchmod='$srchmod' AND dateline>'$_G[timestamp]'-60")) >= $_G['setting']['search']['shop']['maxspm']){
					showmessage('search_toomany', 'search.php?mod=shop', array(
							'maxspm'=>$_G['setting']['search']['shop']['maxspm']
					));
				}
			}

			$num = $ids = 0;
			$_G['setting']['search']['shop']['maxsearchresults'] = $_G['setting']['search']['shop']['maxsearchresults'] ? intval($_G['setting']['search']['shop']['maxsearchresults']) : 500;

			if (! empty($srchfrom)){
				$searchfrom = $before ? '<=' : '>=';
				$searchfrom .= TIMESTAMP - $srchfrom;
				$condition .= " AND lastupdate$searchfrom";
				$expiration = TIMESTAMP + $cachelife_time;
			}

			if (! empty($keyword)){
				$mySelect .= ", if(pname LIKE '{$keyword}', 50, 1) +
							if(pname LIKE '%{$keyword}%', 50, 2) +
							if(pname LIKE '%{$keyword}', 50, 3) +
							if(pname LIKE '{$keyword}%', 50, 4) +

							if(pcode LIKE '{$keyword}', 50, 1) +
							if(pcode LIKE '%{$keyword}%', 50, 2) +
							if(pcode LIKE '%{$keyword}', 50, 3) +
							if(pcode LIKE '{$keyword}%', 50, 4)";

				if (! empty($mySelect)){
					$mySelect .= ' AS nPoint';
					$mySqli = 'HAVING nPoint >= 50';
					$myOrder = 'nPoint DESC, lastupdate ' . $ascdesc;
				}
			}

			$sql = ("SELECT pid" . $mySelect . "
					FROM " . DB::table('shop_products') . "
					WHERE " . $condition . "
					" . $mySqli . "
					ORDER BY " . $myOrder . "
					LIMIT 0, " . $_G['setting']['search']['shop']['maxsearchresults']);
//echo $sql;
//exit();
			$query = mysql_query($sql);

			while ($row = DB::fetch($query)){
				$ids .= ',' . $row['pid'];
				$num++;
			}
			DB::free_result($query);

			$keywords = str_replace(' ', '+', $srchtxt);
			$expiration = TIMESTAMP + $cachelife_text;

//			echo '$keywords: ' , $keywords , '<br />';
//			echo '$kwhtm: ' , $kwhtm , '<br />';

			$Qry_insert = "INSERT INTO " . DB::table('common_searchindex') . " (srchmod, keywords, searchstring, useip, uid, dateline, expiration, num, ids)
							VALUES ('$srchmod', '$keywords', '$searchstring', '$_G[clientip]', '$_G[uid]', '$_G[timestamp]', '$expiration', '$num', '$ids')";
//			echo $Qry_insert;
//			exit();

			DB::query($Qry_insert);
			$searchid = DB::insert_id();
		}

		dheader("location: search.php?mod=shop&searchid=$searchid&orderby=$orderby&ascdesc=$ascdesc&searchsubmit=yes&kw=" . urlencode($keyword));
	}
}